#! /usr/bin/env python
import sys
import shutil
import os

def modify(filepath="/etc/environment",path=""):
	filepath_copy = filepath + ".copy"
	tmp = filepath + ".tmp"
	print "filepath argunemt is empty use default %s." % filepath
	if "" == path:
		print "path is empty,exit!"
		sys.exit()
	shutil.copy(filepath,tmp)
	f = open(tmp,"r+")
	try:
		for line in f:
			if line.startswith("PATH"):
				idx = line.rindex('"')
				newpath = line[0:idx]
				if not path.startswith(":"):
					newpath += ":"
				newpath += path
				newpath += '"'
				print "new path is %s." % newpath
				f.seek(0)
				f.writelines(newpath)
				f.flush()
				f.close()
				if(os.path.exists(filepath_copy)):
					os.system("rm -rf " + filepath_copy)
				shutil.move(filepath,filepath_copy)
				shutil.move(tmp,filepath)
				os.system("rm -rf " + tmp)
	except:
		if not f.closed:
			f.close()
		os.system("rm -rf " + tmp)
	finally:
		if not f.closed:
			f.close()
		print "modify the path settint is over."

if "__main__" == __name__:
	modify("/opt/sys/src/env",path="/usr/java")
